<?php

class Workset_File_Info_Helper {

    const T_IMAGE       = 1;
    const T_FILE        = 2;

    protected static $_infoClasses = array(
        self::T_IMAGE       => 'Workset_File_Info_Image',
        self::T_FILE        => 'Workset_File_Info',
    );

    protected static $_mimeTypes = array(
        'image/gif'     => self::T_IMAGE,
        'image/jpeg'    => self::T_IMAGE,
        'image/png'     => self::T_IMAGE,
        'image/bmp'     => self::T_IMAGE
    );

    protected static $_defaultInfoClass = 'Workset_File_Info';

    protected static $_magicFile = null;

    protected static $_mimeType = null;

    static function createInfo($filename, $realpath = true) {
        $class = self::getInfoClass($filename, $realpath);
        return new $class($filename, $realpath);
    }

    static function getInfoClass($filename, $realpath = true) {
        if (false == $realpath) {
            $filename = Workset_File_Info::getFullPath($filename);
        }

        $mime = self::getMimetype($filename);

        if (is_string($mime) && isset(self::$_mimeTypes[$mime])) {
            $class = self::$_infoClasses[ self::$_mimeTypes[$mime] ];
        } else {
            $class = self::$_defaultInfoClass;
        }

        return $class;
    }

    static function getMimetype($filename) {
        $detect = defined('FILEINFO_MIME_TYPE') ? FILEINFO_MIME_TYPE : (defined('FILEINFO_MIME') ? FILEINFO_MIME : null);

        if (null !== $detect) {
            if ($finfo = new finfo($detect, self::$_magicFile)) {

                $mime = $finfo->file($filename);

                if ($mime) {
                    return $mime;
                }
            }
        }

        return self::$_mimeType;
    }

}

?>